package com.loiot.commons.jms;




import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

/**
 * @author wangzx $Id$
 * 
 */
public class ActiveMqClient {
    
    private static final Logger logger = LoggerFactory.getLogger(ActiveMqClient.class);
    
    private static  JmsTemplate jmsTemplate;

    /**
     * 发送消息
     * @param topicName
     * @param jsonStr
     * @throws Exception
     */
    public static void sendMessage(String topicName , final String jsonStr) throws Exception {
        //设置消息持久性
        //如果不想持久化可以DeliveryMode.NON_PERSISTENT
        jmsTemplate.setDeliveryMode(DeliveryMode.PERSISTENT);
        
        jmsTemplate.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE);
        
        jmsTemplate.send(topicName, new MessageCreator(){
            public Message createMessage(Session session) throws JMSException {
                ObjectMessage om = null;
                try {
                    om = session.createObjectMessage(jsonStr);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return om;
            }
        });
    }
   
    public JmsTemplate getJmsTemplate() {
        return jmsTemplate;
    }

    public void setJmsTemplate(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }


}
